import { useState, useRef } from "react";
import ReactCrop from "react-image-crop";
import "react-image-crop/dist/ReactCrop.css";
import Modal from "../../Modal/Modal";

const Cropper = ({ showModal, onModalClose, imgURL, onSaveHandler }) => {
  const imageStore = useRef(null);
  const [crop, setCrop] = useState({
    unit: "%",
    x: 0,
    y: 0,
    width: 50,
    aspect: 16 / 9,
  });
  const [croppedImageUrl, setCroppedImageUrl] = useState("");

  const makeClientCrop = async (crop) => {
    if ((imageStore, crop.width && crop.height)) {
      const croppedImg = await getCroppedImg(
        imageStore.current,
        crop,
        "newFile.jpeg"
      );
      setCroppedImageUrl(croppedImg);
    }
  };

  const getCroppedImg = (image, crop, fileName) => {
    const canvas = document.createElement("canvas");
    const pixelRatio = window.devicePixelRatio;
    const scaleX = image.naturalWidth / image.width;
    const scaleY = image.naturalHeight / image.height;
    const ctx = canvas.getContext("2d");

    canvas.width = crop.width * pixelRatio * scaleX;
    canvas.height = crop.height * pixelRatio * scaleY;

    ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
    ctx.imageSmoothingQuality = "high";

    ctx.drawImage(
      image,
      crop.x * scaleX,
      crop.y * scaleY,
      crop.width * scaleX,
      crop.height * scaleY,
      0,
      0,
      crop.width * scaleX,
      crop.height * scaleY
    );

    try {
      return new Promise((resolve) => {
        canvas.toBlob((blob) => {
          const files = new window.File([blob], "test", { type: blob?.type });
          console.log('🚀 ~ file: ReactImageCrop.jsx ~ line 57 ~ canvas.toBlob ~ files', files);
          let base64Url = URL.createObjectURL(blob);
          resolve(base64Url);
        }, "image/jpeg");
      });
    } catch (error) {
      console.log(error);
      return null;
    }
  };

  return (
    <Modal
      showModal={showModal}
      onSaveHandler={() => onSaveHandler(croppedImageUrl)}
      onModalClose={onModalClose}
    >
      <ReactCrop
        src={imgURL}
        crop={crop}
        ruleOfThirds
        onImageLoaded={(img) => {
          console.log(img);
          //setImage(img);
          imageStore.current = img;
        }}
        onComplete={(crop) => makeClientCrop(crop)}
        onChange={(cropData) => setCrop(cropData)}
      />
    </Modal>
  );
};

export default Cropper;
